package com.ly.ql.Wms.Service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.ql.RocketMqListener.Produce.ProduceUtils;
import com.ly.ql.Wms.Bill.InStockBill;
import com.ly.ql.Wms.Entity.InStockDetailEntity;
import com.ly.ql.Wms.Entity.InStockHeadEntity;
import com.ly.ql.Wms.Mapper.InStockBillDataMapper;
import com.ly.ql.Wms.Mapper.InStockBillMapper;
import com.ly.ql.Wms.Result.InStockBillPushResult;
import com.ly.ql.Wms.Service.InStockBillDataService;
import com.ly.ql.Wms.Service.InStockBillPushService;
import com.ly.ql.Wms.utils.IdGenerate;
import com.ly.ql.Wms.utils.LoginUtils;
import com.ly.ql.Wms.utils.RequestK3Utils;
import com.ly.ql.Wms.utils.TypeSafeUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class InStockBillDataServiceImpl extends ServiceImpl<InStockBillDataMapper, InStockBill> implements InStockBillDataService {
    @Value(value = "${k3.PullUrl}")
    private String k3PullUrl;

    @Value(value = "${k3.k3AuditUrl}")
    private String k3AuditUrl;

    private final ProduceUtils produceUtils;

    private final LoginUtils loginUtils;

    private final InStockBillMapper inStockBillMapper;
    @Override
    public void InsertBill(String ErpNo,String FormId) {
        Map ParamSelect = new HashMap<>();
        LinkedHashMap dataSelect = new LinkedHashMap<>();
        if ("PUR_ReceiveBill".equals(FormId)){
            dataSelect.put("FormId",FormId);
            dataSelect.put("FieldKeys", "FDemandOrgId.FNumber,FDate,FSupplierId.FNumber,FNote,FDetailEntity_FEntryID,FMaterialId.FNumber,FMateriaModel,FLot.FNumber,F_abc_ZBQSL,FUnitId.FNumber,F_PAEZ_Edition,F_abc_LONGDU,FActReceiveQty,FID,FOrderBillNo,FMaterialId.F_abc_POTFLG,FMaterialId.F_PAEZ_EnableVersion,FCheckInComing,Fbillno,F_PAEZ_BBWLMC,F_PAEZ_BBWLGGXH,FStockOrgId.FNumber,FStockID.FNumber,F_PAEZ_WMSCW.FNumber,FDescription,FOrderBillNo,FDetailEntity_FSEQ");
            dataSelect.put("FilterString", "FBillNo IN ('') OR (FStockOrgId.FNumber IN ('JZX','HT','KLLN','SKLL') and (LEFT(FMaterialId.FNumber,2) IN ('51') OR LEFT(FMaterialId.FNumber,1) IN ('4','3')) AND (F_PAEZ_TJTIME>='2024-09-22 10:39:46' AND F_PAEZ_TJTIME <= '2024-10-15 08:52:16') AND FDocumentStatus ='C')");
            ParamSelect.put("data", dataSelect);
        }
        try {
            String Cookie = loginUtils.getLogin();
            Map<String, String> headMap = new HashMap<>();
            headMap.put("Cookie", Cookie);
            String pullResult = RequestK3Utils.sendDataByJson(k3PullUrl, JSONObject.toJSONString(ParamSelect, SerializerFeature.DisableCircularReferenceDetect), headMap);
            JSONArray Result = JSONArray.parseArray(pullResult);
            LinkedList<InStockBill> listInStockBill =new LinkedList<>();
            Map<String,InStockBill> inStockBillMap =new LinkedHashMap<>();
            if (Result.size()>0){
                if ("PUR_ReceiveBill".equals(FormId)){
                    //写入表单(需要先根据查询来的数据进行分组)
                    for (Object o : Result) {
                        Map<String,Object> map= (Map<String, Object>) o;
                        String key = TypeSafeUtils.TypeToString(map.get("Fbillno"))+map.get("FID")+map.get("FDemandOrgId.FNumber")+"";
                        InStockDetailEntity detailEntity = new InStockDetailEntity();
                        detailEntity.setOID(IdGenerate.newOID());
                        detailEntity.setCREATOR(loginUtils.getUserId());
                        detailEntity.setErpDetailId(TypeSafeUtils.typeToLong(map.get("FDetailEntity.FEntryID")));
                        detailEntity.setBasicQty(TypeSafeUtils.typeToDecimal(map.get("F.abc.ZBQSL")));
                        detailEntity.setBatchNo(TypeSafeUtils.TypeToString(map.get("FLot.FNumber")));
                        detailEntity.setConcentration((Boolean)map.get("FMaterialId.F.abc.POTFLG")==false?new BigDecimal(100.00): TypeSafeUtils.typeToDecimal(map.get("F.abc.LONGDU")));
                        detailEntity.setIsReceiveQc((Boolean) map.get("FCheckInComing")==true ? 1:0);
                        detailEntity.setQty(detailEntity.getBasicQty());
                        detailEntity.setDiscountQty((Boolean)map.get("FMaterialId.F.abc.POTFLG")==false?detailEntity.getBasicQty():detailEntity.getBasicQty().multiply(detailEntity.getConcentration().divide(new BigDecimal(100)).setScale(12, RoundingMode.HALF_UP)).setScale(6,RoundingMode.HALF_UP));
                        detailEntity.setVersionCode((Boolean)map.get("FMaterialId.F.PAEZ.EnableVersion")==false?"*":TypeSafeUtils.TypeToString(map.get("F.PAEZ.Edition")));
                        detailEntity.setSpec(TypeSafeUtils.TypeToString(map.get("FMateriaModel")));
                        HashMap condition= new HashMap<>();
                        condition.put("Code",map.get("FUnitId.FNumber"));
                        detailEntity.setMaterialUnit(TypeSafeUtils.TypeToString(inStockBillMapper.selectNameByCondition("LRP_MaterialUnit",condition).get("name")));
                        condition.put("Code",map.get("FStockOrgId.FNumber").toString()+"|"+map.get("FMaterialId.FNumber"));
                        detailEntity.setMaterialId(inStockBillMapper.selectIdByCondition("lrp_material",condition));
                        condition.put("Code",map.get("FStockOrgId.FNumber").toString()+"|"+map.get("FStockID.FNumber"));
                        detailEntity.setStoreroomId(inStockBillMapper.selectIdByCondition("lrp_storeroom",condition));
                        condition.put("Code",map.get("FStockOrgId.FNumber").toString()+"|"+map.get("F.PAEZ.WMSCW.FNumber"));
                        detailEntity.setLocationId(inStockBillMapper.selectIdByCondition("lrp_location",condition));
                        detailEntity.setVersionName(TypeSafeUtils.TypeToString(map.get("F.PAEZ.BBWLMC")));
                        detailEntity.setVersionMode(TypeSafeUtils.TypeToString(map.get("F.PAEZ.BBWLGGXH")));
                        detailEntity.setERPLineID(TypeSafeUtils.typeToInteger(map.get("FDetailEntity.FSEQ")));
                        if (inStockBillMap.containsKey(key)){
                            detailEntity.setSOID(inStockBillMap.get(key).getInStockHeadEntity().getSOID());
                            inStockBillMap.get(key).getInStockDetailEntity().add(detailEntity);
                        }else {
                            InStockHeadEntity headEntity=new InStockHeadEntity();
                            headEntity.setOID(IdGenerate.newOID());
                            condition.put("Code",TypeSafeUtils.TypeToString(map.get("FStockOrgId.FNumber")));
                            headEntity.setWarehouseCenterId(inStockBillMapper.selectIdByCondition("lrp_warehousecenter", condition));
                            headEntity.setFormId(FormId);
                            headEntity.setIsReceiveQc((Boolean) map.get("FCheckInComing")==true ? 1:0);
                            headEntity.setErpHeadId(TypeSafeUtils.typeToLong(map.get("FID")));
                            headEntity.setCREATOR(loginUtils.getUserId());
                            headEntity.setOwnerNo(TypeSafeUtils.TypeToString(map.get("Fbillno")));
                            headEntity.setExpectDateTimeFrom(LocalDateTime.parse(TypeSafeUtils.TypeToString(map.get("FDate")), DateTimeFormatter.ISO_LOCAL_DATE_TIME));
                            detailEntity.setSOID(headEntity.getOID());
                            InStockBill inStockBill =new InStockBill();

                            inStockBill.setInStockHeadEntity(headEntity);
                            LinkedList<InStockDetailEntity> InStockDetailList =new LinkedList<>();
                            InStockDetailList.add(detailEntity);
                            inStockBill.setInStockDetailEntity(InStockDetailList);
                            inStockBillMap.put(key,inStockBill);
                        }
                    }
                    inStockBillMap.entrySet().forEach(Entity->{
                        // 表单集合 循环插入或更新数据库(状态大于200 则 去除)

                        InStockBill bill = Entity.getValue();
                        HashMap condition= new HashMap<>();
                        condition.put("ErpHeadId",bill.getInStockHeadEntity().getErpHeadId());
                        condition.put("OwnerNo",bill.getInStockHeadEntity().getOwnerNo());
                        condition.put("OwnerId",bill.getInStockHeadEntity().getErpHeadId());
                        Integer Status = TypeSafeUtils.typeToInteger(inStockBillMapper.selectNameByCondition("LRP_MaterialUnit", condition).get("Status"));
                        try {
                            if (Status>0&&Status<=200){ //执行插入
                                int insert = baseMapper.insert(bill);
                                System.out.println(insert);
                            }
                        }catch (Exception e){
                            throw new RuntimeException("单据保存失败，金蝶单号为："+bill.getInStockHeadEntity().getOwnerNo()+"异常为："+e.getMessage());
                        }
                    });

                }
            }else if (Result.size()==0){
                //打印请求日志 写入日志框架
            }
        }catch (Exception e){
            //推送MQ处理 发送邮件

            System.out.println(e.getMessage());
        }
    }
}
